<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;
use StudyBuddy\Paginator;
use StudyBuddy\Template\Urhere;

/**
 * Controller to view unanswered questions
 * pages. Unanswered pages could show:
 * no accepted answer, no answer at all,
 * tagged unanswered and 'my unanswered'
 *
 * In any case the 'tags' block will always be showing
 * "unanswered" tags
 * 
 */
class Unanswered extends Viewquestions
{

	/**
	 * Indicates the current tab
	 *
	 * @var string
	 */
	protected $qtab = 'unanswered';

	protected $pagerPath = '/unanswered';


	protected $aTags;

	/**
	 * Tags string from url
	 * it is urldecoded
	 *
	 * @var string
	 */
	protected $tags = '';

	/**
	 * Tags
	 */
	protected $rawTags = '';


	/**
	 * Select items according to conditions passed in GET
	 * Conditions can be == 'unanswered', 'hot', 'recent' (default)
	 */
	protected function getCursor(){


		$cond = $this->oRequest->get('cond', 's', 'recent');
		d('cond: '.$cond);

		/**
		 * Default sort is by timestamp Descending
		 * meaning most recent should be on top
		 *
		 */
		$sort = array('i_ts' => -1);
		/**
		 * @todo translate this title later
		 *
		 */
		$this->title = 'Questions with no accepted answer';

		switch($cond){


			/**
			 * Most answers/comments/views
			 * There is an activity counter
			 * 1 point per view, 10 point per comment,
			 * 50 points per answer
			 * but still limit to 30 days
			 * Cache Tags for 1 day only
			 * uncache onQuestionVote, onQuestionComment
			 */
			case 'noanswer':
				$this->title = $this->_('Questions with no answers');
				$this->pagerPath = '/unanswered/noanswers';
				$where = array('i_ans' => 0);
				$this->typeDiv = Urhere::factory($this->oRegistry)->get('tplQuntypes', 'noanswer');
				break;

			case 'tagged':
				$where = array('i_sel_ans' => null, 'a_tags' => array('$all' => $this->getTags()) );
				$this->pagerPath = '/unanswered/tagged/'.$this->rawTags;
				$this->typeDiv = Urhere::factory($this->oRegistry)->get('tplQuntypes', 'newest');
				$this->makeFollowTagButton();
				$replaced = \str_replace(' ', ' + ', $this->tags);
				$this->counterTaggedText = \tplCounterblocksub::parse(array($replaced, $this->_('Tagged')), false);
				break;

				/**
				 * Default is all questions
				 * with no selected answer!
				 */
			default:
				$this->title = $this->_('Questions with no accepted answer');
				$where = array('i_sel_ans' => null);
				$this->typeDiv = Urhere::factory($this->oRegistry)->get('tplQuntypes', 'newest');
		}

		/**
		 * Exclude deleted items
		 */
		$where['i_del_ts'] = null;

		$this->oCursor = $this->oRegistry->Mongo->QUESTIONS->find($where, $this->aFields);
		$this->count = $this->oCursor->count(true);
		d('$this->oCursor: '.gettype($this->oCursor).' $this->count: '.$this->count);
		$this->oCursor->sort($sort);

		return $this;
	}



	protected function addTagFollowers(){
		$s = \StudyBuddy\ShowFollowers::factory($this->oRegistry)->getTagFollowers($this->aTags[0]);
		d('tag followers: '.$s);
		$this->aPageVars['side'] .= '<div class="fr cb w90 lg rounded3 pl10 mb10">'.$s.'</div>';

		return $this;
	}


	/**
	 * Extract value of tags from
	 * query string and turn into array
	 * runs value of Request through urldecode because
	 * unicode tags would be percent-encoded in the url
	 *
	 * @return array of tags passed in query string
	 */
	protected function getTags(){
		if(empty($this->aTags)){

			/**
			 * And now a workaround
			 * for the genocidal RewriteRule bug
			 * that obliterates the urlencoded chars
			 * during the rewrite
			 * so instead we must work directly
			 * with $_SERVER['REQUEST_URI']
			 * $_SERVER['REQUEST_URI'] is consistently
			 * the same on Apache and on Lighttpd when
			 * php is run as fastcgi
			 * The rewrite on Lighttpd does not have
			 * this genocidal bug, but for consistency
			 * we still working with $_SERVER['REQUEST_URI']
			 * regardless of the server
			 */
			if(!empty($_SERVER) && !empty($_SERVER['REQUEST_URI'])){
				/**
				 * Must use regex because REQUEST_URI
				 * may contain also a pageID after the last /
				 * so must extract part from
				 * between /tagged/ and next /
				 *
				 * $r is something like this: /tagged/tag%2B%2B/
				 */
				$r = $_SERVER['REQUEST_URI'];
				$m = \preg_match('/\/tagged\/([^\/]+)([\/]{0,1})/i', $r, $matches);
							
				d('matches: '.print_r($matches, 1));
				if($matches && !empty($matches[1])){
					$tags = $matches[1];
					d('tags: '.$tags);
					$this->tags = \urldecode($tags);
				}

			} else {
				/**
				 * That's hopefully is OK
				 * because Apache always has REQUEST_URI
				 * and if it's not available here
				 * then hopefully this is not an Apache server
				 * and it's possible the rewrite worked without this bug
				 */
				d('no REQUEST_URI available');
				$tags = $this->oRequest['tags'];
				$this->tags = \urldecode($tags);
			}

			$this->rawTags = $tags;
			$this->title = $this->tags;
			d('this->title: '.$this->title);
				
			if(empty($this->tags)){
				return array();
			}
				
			$this->aTags = \explode(',', $this->tags);
			$this->aTags = \array_filter($this->aTags);
			d('aTags: '.\print_r($this->aTags, 1));
		}

		return $this->aTags;
	}


	/**
	 * @todo translate word "Unanswered"
	 *
	 * @see wwwViewquestions::makeRecentTags()
	 */
	protected function makeRecentTags(){

		/**
		 * If user is logged in AND
		 * has 'followed tags' then don't use
		 * cache and instead do this:
		 * get array of recent tags, sort in a way
		 * than user's tags are on top and then render
		 * This way user's tags will always be on top
		 * at a cost of couple of milliseconds we get
		 * a nice personalization that does increase
		 * the click rate!
		 * */
		$aUserTags = $this->oRegistry->Viewer['a_f_t'];
		if(!empty($aUserTags)){
			$s = $this->getSortedRecentTags($aUserTags, 'unanswered');
		} else {
			$s = $this->oRegistry->Cache->qunanswered;
		}

		$tags = \tplBoxrecent::parse(array('tags' => $s, 'title' => $this->_('Unanswered tags')));
		$this->aPageVars['tags'] = $tags;

		return $this;
	}



	protected function makeCounterBlock(){
		$this->aPageVars['topRight'] = \tplCounterblock::parse(array($this->count, $this->title, $this->counterTaggedText), false);

		return $this;
	}


	/**
	 * Make html of the 'Follow this tag' button
	 * Check is user is already following it, then
	 * shows 'Following' button
	 * Sets the value of $this->aPageVars['side']
	 * to be the div with follow button
	 *
	 * @return object $this
	 *
	 */
	protected function makeFollowTagButton(){

		/**
		 * Only show the follow tag button
		 * if viewing page about only one tag
		 * a page about multiple tags
		 * will not show follow tag because
		 * it's not clear which tag to follow
		 *
		 */
		if(1 === count($this->aTags)){
			$tag = $this->aTags[0];
			d('tag: '.$tag);

			$aFollowed = $this->oRegistry->Viewer['a_f_t'];
			d('$aFollowed: '.print_r($aFollowed, 1));

			$aVars = array(
			'id' => $tag,
			'icon' => 'cplus',
			'label' => $this->_('Follow this tag'),
			'class' => 'follow',
			'type' => 't',
			'title' => $this->_('Follow this tag to be notified when new questions are added')
			);

			if(in_array($tag, $aFollowed)){
				$aVars['label'] = $this->_('Following');
				$aVars['class'] = 'following';
				$aVars['icon'] = 'check';
				$aVars['title'] = $this->_('You are following this tag');
			}

			$this->aPageVars['side'] = '<div class="fr cb w90 lg rounded3 pl10 mb10"><div class="follow_wrap">'.\tplFollowButton::parse($aVars, false).'</div></div>';

			$this->addTagFollowers();

		}

		return $this;
	}
}
